package com.westos.dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.westos.domain.Customer;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Properties;

/**
 * @Author: ShenMouMou
 * @CreateTime: 2019-12-27 14:05
 * @Company:西部开源教育科技有限公司
 * @Description:爱生活，爱Java!
 */
public class CustomerDao {

    private DataSource dataSource;

    private QueryRunner queryRunner;

    public QueryRunner getQueryRunner() {
        return queryRunner;
    }

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public List<Customer> findAllCustomer() throws Exception {
        //查询数据库

        List<Customer> list = queryRunner.query("select * from customer", new BeanListHandler<Customer>(Customer.class));
        return list;
    }

    public boolean addCustomer(Customer customer) throws Exception {
        //查询数据库

        int i = queryRunner.update("insert into customer values(?,?,?,?,?,?,?)", customer.getCid(), customer.getCname(), customer.getAge(), customer.getGender(), customer.getEmail(), customer.getTelephone(), customer.getDescription());
        return i>0;
    }

    public boolean delCustomer(String cid) throws Exception {

        int i = queryRunner.update("delete from customer where cid=?", cid);
        return i>0;
    }

    public boolean delAllCustomer(String[] item_checkboxes) throws Exception {
  Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("delete from customer where cid=?");
        for (String cid : item_checkboxes) {
            preparedStatement.setString(1,cid);
            preparedStatement.addBatch();
        }
        int[] ints = preparedStatement.executeBatch();
        preparedStatement.clearBatch();
        return ints.length>0;
    }
}
